package com.blog.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {
    //声明一个数据对象
    private static DruidDataSource dataSource;
    static{
        Properties properties = new Properties();
        InputStream is = DruidDataSource.class.getResourceAsStream("/druid.properties");
        try {
            properties.load(is);
            //创建数据源对象
             dataSource =(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //获取数据源对象
    public static DataSource getDataSource() {
        return dataSource;
    }
    //获取数据库连接
    public static Connection getConnection(){
        try {
            Connection connection = (Connection)dataSource.getConnection();
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    //释放数据库连接
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
            if(statement!=null){
                statement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);

        }
    }

}
